package com.example.springboot3.interceptor;

import com.example.springboot3.context.UserContext;
import com.example.springboot3.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 张琪
 * @date 2024-02-26 14:41
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static Set<String> whiteList =  new HashSet<>();

    static {
        whiteList.add("/jwt/login");
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (whiteList.contains(request.getRequestURI())){
            return true;
        }

        Claims authorization = JwtUtil.parse(request.getHeader("Authorization"));

        if (authorization != null){
            UserContext.add(authorization.getSubject());
            return true;
        }

        // 设置响应数据类型为json（前后端分离）
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 设置响应内容，结束请求
        out.write("请先登录");
        out.flush();
        out.close();
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
        // 该语法为 接口调用自身的默认方法
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
